package com.woniu.supermarket.util;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.woniu.supermarket.vo.exportDealSummaryVo;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class ExcelUtil {

    private static final String DATA_FORMAT = "yyyy-MM-dd-HH-mm-ss";

    private static final String CHARACTER_UTF_8 = "UTF-8";

    private static final String CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    private static final String CONTENT_DISPOSITION = "Content-Disposition";

    private static final String CACHE_CONTROL = "Cache-Control";

    private static final String NO_STORE = "no-store";

    private static final String MAX_AGE = "max-age=0";

    private static final Integer PAGE_SIZE = 10000;



    /**
     * 导出excel
     * @param response 返回对象
     * @param list excel 表中记录
     */
    public static void writeExcel(HttpServletResponse response, List<exportDealSummaryVo> list) throws IOException {
        String sheetName = "DealSummary";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATA_FORMAT);
        String nowTime = formatter.format(LocalDateTime.now());

        response.setContentType(CONTENT_TYPE);

        //设置字符集为utf-8
        response.setCharacterEncoding(CHARACTER_UTF_8);

        String fileName = sheetName.concat("_").concat(nowTime).concat(".xlsx");

        //文件名乱码解决：用postman测正常，浏览器多了filename_=utf-8等字样
        response.setHeader(CONTENT_DISPOSITION,
                "attachment;filename=" + URLEncoder.encode(fileName, CHARACTER_UTF_8)
                        + ";filename*=utf-8''" + URLEncoder.encode(fileName, CHARACTER_UTF_8));

        //发送一个报头，告诉浏览器当前页面不进行缓存，每次访问的时间必须从服务器上读取最新的数据
        response.setHeader(CACHE_CONTROL, NO_STORE);
        response.addHeader(CACHE_CONTROL, MAX_AGE);


        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();

        //定义工作表对象
        WriteSheet sheet = EasyExcel.writerSheet(0, sheetName).head(exportDealSummaryVo.class).build();


        //给excel写内容
        excelWriter.write(list,sheet);
        //关闭输出流
        excelWriter.finish();
    }
}
